//
//  ZCWebView.m
//  DoctorOnline
//
//  Created by 赵隆杰 on 2018/8/20.
//  Copyright © 2018年 赵隆杰. All rights reserved.
//

#import "ZCWebView.h"
#import "ZCWKWebViewConfiguration.h"

#define isIos9 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9)

@interface ZCWebView()<WKNavigationDelegate,WKUIDelegate>

@property (strong, nonatomic) ZCWKWebViewConfiguration *wkWebConfig;

@end

@implementation ZCWebView

-(instancetype)init
{
    self = [self initWithFrame:CGRectZero];
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    ZCWKWebViewConfiguration *wkWebConfig = [[ZCWKWebViewConfiguration alloc] init];
    self = [super initWithFrame:frame configuration:wkWebConfig];
    if (self) {
        
        self.wkWebConfig = wkWebConfig;
        [self config];
    }
    
    return self;
    
}

-(void)config
{
    self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    // Action
    VHWeakSelf
    _wkWebConfig.handleBlock = ^(NSDictionary *responseDic) {
        VHStrongSelf
        [self handleJSAction:responseDic];
    };
    
    self.navigationDelegate = self;
    self.UIDelegate = self;
    
}

/// JS事件
-(void)handleJSAction:(NSDictionary *)dic
{
    //
    NSString *click_type = [NSString stringWithFormat:@"%@",[dic objectForKey:@"click_type"]];
    
    if (click_type) {
        if(self.handleJSAtion){
            self.handleJSAtion(click_type.integerValue, dic);
        }
    }
    
}


#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { // 类似UIWebView的 -webViewDidStartLoad:
//    NSLog(@"didStartProvisionalNavigation");
    //    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    if([self.zcWebDelegate respondsToSelector:@selector(webViewStartLoad:)]){
        [self.zcWebDelegate webViewStartLoad:self];
    }
    
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
//    NSLog(@"didCommitNavigation");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // 类似 UIWebView 的 －webViewDidFinishLoad:
//    NSLog(@"didFinishNavigation");
    
    if([self.zcWebDelegate respondsToSelector:@selector(webViewLoadFinished:)]){
        [self.zcWebDelegate webViewLoadFinished:self];
    }
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"%@",error.userInfo);
    
    if([self.zcWebDelegate respondsToSelector:@selector(webViewLoadFailed:)]){
        [self.zcWebDelegate webViewLoadFailed:self];
    }
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
//    NSLog(@"decidePolicyForNavigationResponse");
    decisionHandler(WKNavigationResponsePolicyAllow); // 允许跳转
}
// 点击超链接事件 暂时不用这种方法调用

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"%@",error.userInfo);
    
    if([self.zcWebDelegate respondsToSelector:@selector(webViewLoadFailed:)]){
        [self.zcWebDelegate webViewLoadFailed:self];
    }
}

//// 首次加载 和 点击超链接会走这里
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    
    decisionHandler(WKNavigationActionPolicyAllow); // 允许跳转
    
}


#pragma mark - WKUIDelegate
/*  警告 */
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
#ifdef DEBUG
    [[[UIAlertView alloc] initWithTitle:@"警告框" message:message delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil] show];
#endif
    
    
    completionHandler();
}
///** 确认框 */
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    
#ifdef DEBUG
    [[[UIAlertView alloc] initWithTitle:@"确认框" message:message delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil] show];
#endif
    
    completionHandler(YES);
}
/**  输入框 */
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
#ifdef DEBUG
    
    [[[UIAlertView alloc] initWithTitle:@"输入框" message:prompt delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil] show];
#endif
    
    completionHandler(@"你是谁！");
}
// 创建新的webView
// 可以指定配置对象、导航动作对象、window特性。如果没用实现这个方法，不会加载链接，如果返回的是原webview会崩溃。 ,vr点击事件先走这里，实现这个代理后才会走 decidePolicyForNavigationAction
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    //    https://stackoverflow.com/questions/25713069/why-is-wkwebview-not-opening-links-with-target-blank
    if (!navigationAction.targetFrame.isMainFrame) {
        
        [webView loadRequest:navigationAction.request];
    }
    
    return nil;
}

// 加载https的地址
//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
//    
//    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//        
//        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
//        
//        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
//        
//    }
//}

-(void)dealloc
{
    [_wkWebConfig.userContentController removeScriptMessageHandlerForName:@"AppNative"];
    _wkWebConfig = nil;
}



@end
